"use strict";

/**
 * @auther wtfssd
 * Created by wtfssd on 2017/10/27
 */
import * as React from 'react'
const { Text, ViewStyle, Linking}  = require( "react-native");
import {urlReg} from "../constant";
import {commonStyles} from "../assets/styles/common";
import {TextProperties,ViewStyle} from "react-native";
import {openUrl} from "../utils/tools";


// const urlReg = new RegExp('(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]','g');
interface MyTextProps extends TextProperties {
    /**字体颜色*/
    color?: string,
    /**字号*/
    fontSize?: number ,
    /**加粗*/
    fontWeight?: string,
    /**样式*/
    style?: ViewStyle | object|any,
}

/**
 * 自定义文本控件 解析url
 */
class MyText extends React.Component<MyTextProps, any> {
    static defaultProps = {
        allowFontScaling: false,
        color: '#333',
        fontSize: 14,
        fontWeight: 'normal'
    };

    constructor(props: MyTextProps, context: any) {
        super(props, context);

    }


    static onTextPress(url) {
        openUrl(url);
    };

    static checkLinks(data, result) {
        if (typeof data === 'string') {
            const res = data.split(urlReg);
            const res1 = data.match(urlReg);
            if (res1) {
                let index = 0;
                res.map((item, i) => {
                    if (item.indexOf('http') !== -1 && res1) {
                        result.push(<Text key={i} style={commonStyles.linkText}
                                          onPress={MyText.onTextPress.bind(null, res1[index])}>{res1[index]}</Text>);
                        index = index + 1;
                    } else {
                        result.push(item);
                    }
                });
            } else {
                result.push(data);
            }

        }
        else if (Array.isArray(data)) {
            data.map(item => {
                MyText.checkLinks(item, result);
            })
        } else if (typeof data === 'object') {
            if (data && data['children']) {
                MyText.checkLinks(data.props.children, result);
            }
        }
        return result;
    }


    render() {
        return (
            <Text  {...this.props} style={[{
                color: this.props.color,
                fontSize: this.props.fontSize,
                fontWeight: this.props.fontWeight,
                backgroundColor: 'transparent'
            }, this.props.style]}>{MyText.checkLinks(this.props.children, [])}</Text>
        );
    }
}


export default MyText;